'''获取二进制 数据流
https://www.baidu.com/favicon.ico
'''
import  requests
from urllib import  request
response = requests.get(r'https://www.baidu.com/favicon.ico')
print(response.text)
'''.content 才是正真的字节流，他才是保存文件的内容
不能 .text 保存，因为 .text只是普通的字符串数据，只用作数据解析
不能作为保存文件的数据'''
print(response.content)
# with open('favicon.ico','wb') as f:
#     f.write(response.content)
'''添加headers'''
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64)'
}
url_string = r'http://httpbin.org'
response = requests.get(url_string + 'headers', headers=header)
print(response.text)

'''POST'''
parms = {
    'name': 'Jack Ma',
    'woke': 'CEO'
}
response = requests.post(url_string + '/post',data=parms, headers=header)
print(response.text)
'''响应response的属性'''
response = requests.get(r'http://www.jianshu.com', headers=header)
print(response.status_code, response.reason)
print(response.headers)
print(response.cookies)
print(response.url)
print(response.history)

'''requests 的异常处理机制'''
'''异常1：非 HTTP错误 (1XX~5XX)'''
response = requests.get(r'http://www.jianshu.com/404.html',headers=header)
print(response.status_code)

if not response.status_code == requests.codes.ok:
    print('404-1')

'''异常2：'''
from requests.exceptions import ReadTimeout,ConnectionError,RequestException
try:
    response = requests.get(r'http://httpbin.org/get', timeout=0.25)
    print(response.status_code)
except ReadTimeout:
    print('Time out')
except ConnectionError:
    print('Connection Error')
except RequestException:
    print('Request Error')
'''文件上传'''
file = {
    'file': open('favicon.ico','rb')
}
# response = requests.post(url_string + '/post',headers=header, files=file)
# print(response.text)
'''证书验证'''
'''无证书验证  不行'''
# response = requests.get(r'https://www.12306.cn', headers=header)
# print(response.status_code)

'''关闭证书验证
就算关闭了 还是会警告 不会出现异常错误
'''
response = requests.get(r'https://www.12306.cn', headers=header, verify=False)
print(response.status_code)

'''消除关闭证书验证的警告'''
requests.urllib3.disable_warnings()
response = requests.get(r'https://www.12306.cn', headers=header, verify=False)
print(response.status_code)

